package com.mes.basicdata.dao;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.stereotype.Repository;

import com.bstek.bdf2.core.model.DefaultDept;
import com.bstek.dorado.data.provider.Page;
import com.mes.basicdata.dao.iface.IDeptDao;
import com.mes.basicdata.domain.Dept;
import com.mes.common.dao.BasicDao;

@Repository
public class DeptDao extends BasicDao<Dept> implements IDeptDao{
	
	@Override
	public String getDeptName(String deptUid) throws Exception {
		String id = null;
		Session session = this.getSessionFactory().getCurrentSession();
		String hql = "select deptName from com.mes.basicdata.domain.Dept where deptUid = ?";
		Query query = session.createQuery(hql);
		query.setString(0, deptUid);
		Object obj = query.uniqueResult();
		if (obj != null)
			id = (String) obj;
		return id;
	}
	
	
	@Override
	public void getDepts(Page<Dept> page, Map<String, Object> parameter) throws Exception {
		// TODO Auto-generated method stub
				Map<String, Object> args = new HashMap<String, Object>();
				
				StringBuffer coreHql = new StringBuffer("from "
						+ Dept.class.getName() + " a where 1=1 ");
				
				String deptName = (String) parameter.get("deptName");
				if (StringUtils.isNotEmpty(deptName)) {
					coreHql.append(" and a.deptName like :deptName ");
					args.put("deptName", "%" + deptName + "%");
				}
				String countHql = "select count(*) " + coreHql.toString();
				String hql = coreHql.toString();
				
				Map<String, Object> newArgs = new HashMap<String, Object>();
				String key;
				String newKey;
				Iterator<String> iterator = args.keySet().iterator();
				while(iterator.hasNext()){
					key = (String)iterator.next();
					newKey = key.replace(".", "_");
					newArgs.put(newKey, args.get(key));
					hql = hql.replace(":"+key, ":"+newKey);
					countHql = countHql.replace(":"+key, ":"+newKey);
					
					System.out.println("hql: " + hql);
					System.out.println("countHql: " + countHql);
					System.out.println("newArgs: " + newArgs);
				}
				this.pagingQuery(page, hql, countHql, newArgs);
		}
	
	@Override
	public void updateDefaultDept(DefaultDept defaultDept) throws Exception {
		Session session = this.getSessionFactory().getCurrentSession();
		
		try {
			session.update(defaultDept);
		} finally {
			session.flush();
		}
		
	}

	@Override
	public void deletedefaultDept(DefaultDept defaultDept) throws Exception {
		Session session = this.getSessionFactory().getCurrentSession();
		
		try {
			session.delete(defaultDept);;
		} finally {
			session.flush();
		}
		
	}

	@Override
	public void savedefaultDept(DefaultDept defaultDept) throws Exception {
		Session session = this.getSessionFactory().getCurrentSession();
		
		try {
			session.save(defaultDept);
		} finally {
			session.flush();
		}
		
	}
	
}
